<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    wrapClassName="j-user-select-modal"
    @ok="handleSubmit"
    @cancel="close"
    :zIndex="10001"
    style="top:50px"
    cancelText="关闭"
  >
    <a-card :bordered="false">
      <!--用户列表-->
      <template v-if="!isSequenceApprove">
      用户账号:
      <a-input-search
        style="width: 200px;margin-bottom: 15px;"
        placeholder="请输入账号"
        v-model="queryParam.username"
        @search="onSearch"
      ></a-input-search>
      <a-button @click="searchReset(1)" icon="redo">重置</a-button>
    </template>
      <a-table
        ref="table"
        bordered
        :scroll="scrollTrigger"
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="isSequenceApprove?{}:ipagination"
        :rowSelection="isSequenceApprove?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
        :loading="loading"
        @change="handleTableChange">
      </a-table>
    </a-card>
    <template v-if="isSequenceApprove">
      <p style="margin-left:40px">注:当前节点的用户不可选择，且审批顺序不可调整，如有问题，请联系集团人力资源中心调整</p>
    </template>
    <template v-if="isSequenceApprove" slot="footer">
      <a-button @click.stop="()=>{visible=false}">关闭</a-button>
    </template>
  </a-modal>
</template>

<script>
  import { filterObj } from '@/utils/util'
  import { getUserList,getUserListOrder, queryDepartTreeList, queryUserByDepId } from '@/api/api'
  import { getAction } from '@api/manage'

  export default {
    name: 'ProcessSelectUserModal',
    components: {},
    props: ['modalWidth','title', 'multi', 'userIds', 'sign', 'dataIds','fsign','isSequenceApprove'],
    data() {
      return {
        queryParam: {
          username: ''
        },
        columns: [
          {
            title: '序号',
            align: 'center',
            key:'rowIndex',
            dataIndex: '',
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '用户账号',
            align: 'center',
            dataIndex: 'username'
          },
          {
            title: '用户姓名',
            align: 'center',
            dataIndex: 'realname'
          },
          {
            title: '性别',
            align: 'center',
            dataIndex: 'sex',
            customRender: function (text) {
              if (text === 1) {
                return '男'
              } else if (text === 2) {
                return '女'
              } else {
                return text
              }
            }
          },
          {
            title: '手机',
            align: 'center',
            dataIndex: 'phone'
          },
          {
            title: '部门',
            align: 'center',
            dataIndex: 'orgCodeTxt'
          }
        ],
        scrollTrigger: {},
        dataSource: [],
        selectedRowKeys: [],
        selectUserRows: [],
        selectUserIds: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: false,
          showSizeChanger: true,
          total: 0
        },
        // isorter: {
        //   column: 'createTime',
        //   order: 'desc'
        // },
        // selectedDepIds: [],
        departTree: [],
        visible: false,
        // form: this.$form.createForm(this),
        loading: false,
        // expandedKeys: [],
        queryByIds: '/api/erpmng/sys/user/queryByIds',
        initSign: false
      }
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio';
      }
    },
    watch: {
      userIds: {
        immediate: true,
        handler() {
          let values = this.userIds.split(',') + ','
          this.initUserNames('', values)
        }
      }
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      // this.loadData()
    },
    methods: {
      initUserNames(username = '', userIds) {
        if (this.dataIds) {
          // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
          let values = this.dataIds.split(',') + ','
          let params = {
            pageNo: this.ipagination.current,
            pageSize: this.fsign==1?-1:this.ipagination.pageSize,
            sign: this.sign,
            username: username || values
          }
          this.loading = true
          getUserListOrder(params).then((res) => {
            if (res.success) {
              let selectedRowKeys = []
              let realNames = []
              this.dataSource = []
              // res.result.records.forEach(user => {
              //   if(userIds.includes(user.username)){
              //     realNames.push(user['realname'])
              //     selectedRowKeys.push(user['id'])
              //     this.dataSource.push(user)
              //   }
              // })


              // 处理列表数据的显示
               res.result.records.forEach(user => {
                if (this.dataIds.includes(user.username)) {
                  this.dataSource.push(user)
                }
              })
              // 处理哪个列表数据被选中
              res.result.records.forEach(user => {
                if (userIds.includes(user.username)) {
                  realNames.push(user['realname'])
                  selectedRowKeys.push(user['id'])
                }
              })

               // 当搜索的时候，数据返回是所有，需要对页面的总页码做处理，人为修改总页数
              this.ipagination.total = res.result.total
              if (selectedRowKeys.length == 1) {
                this.selectedRowKeys = selectedRowKeys
              } else {
                this.selectedRowKeys = []
              }
              if(this.fsign==1||this.initSign){
                this.$emit('initComp', realNames.join(','))
              }
            }
          }).finally(() => {
            this.loading = false
          })
        } else {
          // JSelectUserByDep组件bug issues/I16634
          if(this.fsign==1||this.initSign){
            this.$emit('initComp', '')
          }
        }
      },
      // async loadData(arg) {
      //   if (arg === 1) {
      //     this.ipagination.current = 1;
      //   }
      //   if (this.selectedDepIds && this.selectedDepIds.length > 0) {
      //     await this.initQueryUserByDepId(this.selectedDepIds)
      //   } else {
      //     this.loading = true
      //     let params = this.getQueryParams()//查询条件
      //     await getUserList(params).then((res) => {
      //       if (res.success) {
      //         this.dataSource = res.result.records
      //         this.ipagination.total = res.result.total
      //       }
      //     }).finally(() => {
      //       this.loading = false
      //     })
      //   }
      // },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = { x: 800 };
        } else {
          this.scrollTrigger = {};
        }
      },
      showModal() {
        // this.queryDepartTree();
        if (!this.userIds) {
          this.$message.warning('请联系管理员配置')
          return
        }
        this.visible = true;
        let values = this.userIds.split(',') + ','
        this.initUserNames('', values)
        // this.loadData();
        // this.form.resetFields();
      },
      // getQueryParams() {
      //   let param = Object.assign({}, this.queryParam, this.isorter);
      //   param.field = this.getQueryField();
      //   param.pageNo = this.ipagination.current;
      //   param.pageSize = this.ipagination.pageSize;
      //   param.sign = this.sign;
      //   return filterObj(param);
      // },
      // getQueryField() {
      //   let str = 'id,';
      //   for (let a = 0; a < this.columns.length; a++) {
      //     str += ',' + this.columns[a].dataIndex;
      //   }
      //   return str;
      // },
      searchReset(num) {
        let that = this;
        if (num !== 0) {
          that.queryParam = {};
          that.selectedDepIds = [];
          // that.loadData(1);
          let values = this.userIds.split(',') + ','
          this.initUserNames('', values)
        }
        that.selectedRowKeys = [];
        that.selectUserIds = [];
        that.selectedDepIds = [];
      },
      close() {
        this.searchReset(0);
        this.visible = false;
      },
      handleTableChange(pagination, filters, sorter) {
        if (this.isSequenceApprove) {
          return false
        }
        // TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc';
        }
        this.ipagination = pagination;
        // this.loadData();
        let values = this.userIds.split(',') + ','
        this.initSign = false
        this.initUserNames('', values)
      },
      handleSubmit() {
        let userIds = ''
        if (this.selectedRowKeys.length > 0) {
          getAction(this.queryByIds, { userIds: this.selectedRowKeys.join(',') }).then(res => {
            if (res.success) {
              this.selectUserRows = res.result
              res.result.forEach(item => {
                userIds = userIds + ',' + item.username
              })
            } else {
              this.selectUserRows = []
              this.$message.warning(res.message)
            }
            this.selectUserIds = userIds.substring(1);
            this.$emit('ok', this.selectUserRows, this.selectUserIds);
            this.initSign = true
            this.searchReset(0)
            this.close();
          })
        } else {
          this.selectUserRows = []
          this.selectUserIds = ''
          this.$message.warning('请选择用户')

          // this.$emit('ok', this.selectUserRows, this.selectUserIds);
          // this.searchReset(0)
          // this.close();
        }
      },
      // 获取选择用户信息
      getSelectUserRows() {
        // let dataSource = this.dataSource;
        // let userIds = "";
        // this.selectUserRows = [];
        // for (let i = 0, len = dataSource.length; i < len; i++) {
        //   if (this.selectedRowKeys.includes(dataSource[i].id)) {
        //     this.selectUserRows.push(dataSource[i]);
        //     userIds = userIds + "," + dataSource[i].username
        //   }
        // }
        // this.selectUserIds = userIds.substring(1);
      },
      // 点击树节点,筛选出对应的用户
      // onDepSelect(selectedDepIds) {
      //   if (selectedDepIds[0] != null) {
      //     this.initQueryUserByDepId(selectedDepIds); // 调用方法根据选选择的id查询用户信息
      //     if (this.selectedDepIds[0] !== selectedDepIds[0]) {
      //       this.selectedDepIds = [selectedDepIds[0]];
      //     }
      //   }
      // },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
        // this.selectionRows = selectionRows;
      },
      onSearch(val) {
        let ids = this.userIds.split(',') + ','
        if (!val) {
          this.initUserNames('', ids)
        }
        if (!this.dataIds.includes(val)) {
          this.dataSource = []
          this.ipagination.total = 0 // 人为修改总页数
        } else {
          this.initUserNames(val, ids)
        }
      },
      // 根据选择的id来查询用户信息
      initQueryUserByDepId(selectedDepIds) {
        this.loading = true
        return queryUserByDepId({ id: selectedDepIds.toString(), sign: this.sign }).then((res) => {
          if (res.success) {
            this.dataSource = res.result;
            this.ipagination.total = res.result.length;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      queryDepartTree() {
        queryDepartTreeList().then((res) => {
          if (res.success) {
            this.departTree = res.result;
            // 默认展开父节点
            this.expandedKeys = this.departTree.map(item => item.id)
          }
        })
      }
    }
  }
</script>

<style scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>
